import Request from "@/lib/request/index.js";

import storage from "@/utils/storage.js";
import api from "@/config/api.js";

let isNavigateTo = false
const platformList=[
	{
		uniPlatform:"app",
		netPlatform:"APP"
	},
	{
		uniPlatform:"web",
		netPlatform:"H5"
	},
	{
		uniPlatform:"mp-weixin",
		netPlatform:"WECHAT_MP"
	},
	{
		uniPlatform:"mp-alipay",
		netPlatform:"ALIPAY_MP"
	},
	{
		uniPlatform:"mp-toutiao",
		netPlatform:"DOUYIN_MP"
	},
	{
		uniPlatform:"mp-kuaishou",
		netPlatform:"KUAISHOU_MP"
	}
]
const uniPlatform=uni.getSystemInfoSync().uniPlatform
const client = platformList[platformList.findIndex(i=>i.uniPlatform==uniPlatform)].netPlatform
function cleanStorage() {
	uni.showToast({
		title: "你的登录状态已过期，请重新登录",
		icon: "none",
		duration: 1500,
	});
	if (uni.showLoading()) {
		uni.hideLoading();
	}
	if (!isNavigateTo) {
		isNavigateTo = true
		// 防抖处理跳转
		// #ifdef MP-WEIXIN
		uni.navigateTo({
			url: "/pages/login/wechatMPLogin",
		});
		// #endif
		// #ifdef MP-ALIPAY
		uni.navigateTo({
			url: "/pages/login/aliMPLogin",
		});
		// #endif
	}
	

}

let http = new Request();


http.setConfig((config) => {
	

	/* 设置全局配置 */
	/* 设置全局配置 */
	config.baseURL = api.url;
	config.header = {
		...config.header,
	};
	config.header = {
		...config.header,
	};
	config.validateStatus = (statusCode) => {
		// 不论什么状态,统一在正确中处理
		return true;
	};
	return config;
});

http.interceptors.request.use(
	(config) => {
		let accessToken = storage.getAccessToken();
		if (accessToken) {
			config.header.accessToken = accessToken;
		}
		
		config.header = {
			...config.header,
			clientType:client
		};
		return config;
	},
	(config) => {
		return Promise.reject(config);
	}
);


// 是否正在刷新的标记
let isRefreshing = false;
//重试队列
let requests = [];
// 必须使用异步函数，注意
http.interceptors.response.use(
	async (response) => {
			//if(response.data.code == 10021)
			if (response.data.code == 403) {//未登录
				cleanStorage();
			}else if(response.data.code == 10021){//为绑定房屋
				uni.navigateTo({
					url: "/pages/login/wechatMPLogin",
				});
			}
			return response;
		},
		(error) => {
			return error;
		}
);

export {
	http
};

export const Method = {
	GET: "GET",
	POST: "POST",
	PUT: "PUT",
	DELETE: "DELETE",
};
